package com.hiultra.archive.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.hiultra.archive.mapper.ArcCabinetMapper;
import com.hiultra.archive.service.IArcCabinetService;
import com.hiultra.common.core.domain.TreeSelect;
import com.hiultra.common.core.domain.entity.ArcCabinet;
import com.hiultra.common.core.domain.entity.ArcShelves;
import com.hiultra.common.exception.ServiceException;
import com.hiultra.common.utils.ArcUtil;
import com.hiultra.common.utils.DateUtils;
import com.hiultra.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 智能柜Service业务层处理
 *
 * @author 李爽
 * @date 2023-08-22
 */
@Service
public class ArcCabinetServiceImpl implements IArcCabinetService {
    @Autowired
    private ArcCabinetMapper arcCabinetMapper;

    /**
     * 查询智能柜
     *
     * @param cabinetId 智能柜主键
     * @return 智能柜
     */
    @Override
    public ArcCabinet selectArcCabinetByCabinetId(Long cabinetId) {
        return arcCabinetMapper.selectArcCabinetByCabinetId(cabinetId);
    }

    /**
     * 查询智能柜列表
     *
     * @param arcCabinet 智能柜
     * @return 智能柜
     */
    @Override
    public List<ArcCabinet> selectArcCabinetList(ArcCabinet arcCabinet) {
        return arcCabinetMapper.selectArcCabinetList(arcCabinet);
    }

    /**
     * 新增智能柜
     *
     * @param arcCabinet 智能柜
     * @return 结果
     */
    @Override
    public int insertArcCabinet(ArcCabinet arcCabinet) {
        int i = 0;
        if (null == arcCabinet.getParentId()) {
            arcCabinet.setParentId(0L);
        }
        arcCabinet.setCreateTime(DateUtils.getNowDate());
        //判断是否已经存在
        ArcCabinet arcCabinetCheck = arcCabinetMapper.checkInsert(arcCabinet);
        if (null == arcCabinetCheck) {
            String cabinetCode = null;
            // 自动生成catalogCode
            // 取出同级最大catalogCode
            String maxCode = arcCabinetMapper.selectMaxCode(arcCabinet.getParentId());
            if (ObjectUtil.isEmpty(maxCode)) {
                cabinetCode = "001";
            } else {
                cabinetCode = ArcUtil.get000NextCode(maxCode);
            }
            if (0 == arcCabinet.getParentId()) {
                arcCabinet.setCabinetCode(cabinetCode);
            } else {
                //查询上级code
                ArcCabinet arcCabinet1 = arcCabinetMapper.selectArcCabinetByCabinetId(arcCabinet.getParentId());
                //组合下级code
                arcCabinet.setCabinetCode(arcCabinet1.getCabinetCode() + cabinetCode);
            }
            arcCabinet.setCreateTime(DateUtils.getNowDate());

            i = arcCabinetMapper.insertArcCabinet(arcCabinet);
        } else {
            throw new ServiceException("存在重复编号，请检查后重试！");
        }
        return i;
    }

    /**
     * 修改智能柜
     *
     * @param arcCabinet 智能柜
     * @return 结果
     */
    @Override
    public int updateArcCabinet(ArcCabinet arcCabinet) {

        int i = 0;
        ArcCabinet tempobj = arcCabinetMapper.checkUpdate(arcCabinet);
        if (null == tempobj) {
            arcCabinet.setUpdateTime(DateUtils.getNowDate());
            i = arcCabinetMapper.updateArcCabinet(arcCabinet);
        } else {
            throw new ServiceException("数据已存在！");
        }
        return i;
    }

    /**
     * 批量删除智能柜
     *
     * @param cabinetIds 需要删除的智能柜主键
     * @return 结果
     */
    @Override
    public int deleteArcCabinetByCabinetIds(Long[] cabinetIds) {
        //删除下级智能柜信息
        arcCabinetMapper.deleteArcCabinetAllInfo(cabinetIds);
        return arcCabinetMapper.deleteArcCabinetByCabinetIds(cabinetIds);
    }

    /**
     * 删除智能柜信息
     *
     * @param cabinetId 智能柜主键
     * @return 结果
     */
    @Override
    public int deleteArcCabinetByCabinetId(Long cabinetId) {
        return arcCabinetMapper.deleteArcCabinetByCabinetId(cabinetId);
    }

    /**
     * 设置智能柜规格
     *
     * @param arcCabinet 智能柜
     * @return 结果
     */
    @Override
    @Transactional
    public int updateGridAndLayer(ArcCabinet arcCabinet) {
        //实际业务逻辑
        Long cabinetId = arcCabinet.getCabinetId();
        Integer layerNum = arcCabinet.getLayerNum();
        Integer gridNum = arcCabinet.getGridNum();

        // 获取层级
        ArcCabinet entityOne = arcCabinetMapper.selectArcCabinetByCabinetId(cabinetId);
        int leve = entityOne.getLeve();
        String cabinetcode = entityOne.getCabinetCode();
        // 获取当前层设置
        Integer layerNumNow = entityOne.getLayerNum();
        Integer gridNumNow = entityOne.getGridNum();
        // 修改层数和格数信息
        arcCabinetMapper.updateArcCabinet(arcCabinet);
        int port = 0;
        if (null != layerNumNow) {

            for (int in = 0; in < layerNumNow; in++) {
//                arcCabinetMapper.delByCode(cabinetcode + "-" + (in + 1));
//                arcCabinetMapper.delByParentCode(cabinetcode + "-" + (in + 1));
                arcCabinetMapper.deleteArcCabinetAllInfoOne(cabinetId);
            }
        }

        for (int i = 0; i < layerNum; i++) {
            ArcCabinet entLay = new ArcCabinet();
            entLay.setCabinetCode(cabinetcode + "-" + (i + 1));
            entLay.setParentId(arcCabinet.getCabinetId());
            entLay.setCabinetName("第" + (i + 1) + "层");
            entLay.setStorehouseId(arcCabinet.getStorehouseId());
            entLay.setGridNum(arcCabinet.getGridNum());
            entLay.setCreateTime(DateUtils.getNowDate());
            entLay.setDelflag(0);
            entLay.setStatus(0);
            entLay.setLeve(2);
            entLay.setOrderPort(arcCabinet.getOrderPort());
            entLay.setZcabinetId(cabinetId);
            arcCabinetMapper.insertArcCabinet(entLay);
            // 添加格子
            for (int z = 0; z < gridNum; z++) {
                port++;
                ArcCabinet entGrid = new ArcCabinet();
                entGrid.setCabinetCode(entLay.getCabinetCode() + "-" + (z + 1));
                entGrid.setParentId(entLay.getCabinetId());
                entGrid.setCabinetName("第" + (z + 1) + "格");
                entGrid.setStorehouseId(arcCabinet.getStorehouseId());
                entGrid.setCreateTime(DateUtils.getNowDate());
                entGrid.setDelflag(0);
                entGrid.setStatus(0);
                entGrid.setLeve(3);
                entGrid.setOrderPort(arcCabinet.getOrderPort());
                entGrid.setGridPort(port + "");
                entGrid.setZcabinetId(cabinetId);
                arcCabinetMapper.insertArcCabinet(entGrid);
            }
        }
        return arcCabinetMapper.updateArcCabinet(arcCabinet);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param arcCabinets 密集架列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildCabinetTreeSelect(List<ArcCabinet> arcCabinets) {
        List<ArcCabinet> cabinetTrees = buildCabinetTree(arcCabinets);
        return cabinetTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param arcCabinets 智能柜列表
     * @return 下拉树结构列表
     */
    public List<ArcCabinet> buildCabinetTree(List<ArcCabinet> arcCabinets) {
        List<ArcCabinet> returnList = new ArrayList<ArcCabinet>();
        List<Long> tempList = new ArrayList<Long>();
        for (ArcCabinet cabinet : arcCabinets) {
            tempList.add(cabinet.getCabinetId());
        }
        for (ArcCabinet cabinet : arcCabinets) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(cabinet.getParentId())) {
                recursionFn(arcCabinets, cabinet);
                returnList.add(cabinet);
            }
        }
        if (returnList.isEmpty()) {
            returnList = arcCabinets;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<ArcCabinet> list, ArcCabinet t) {
        // 得到子节点列表
        List<ArcCabinet> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ArcCabinet tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ArcCabinet> getChildList(List<ArcCabinet> list, ArcCabinet t) {
        List<ArcCabinet> tlist = new ArrayList<ArcCabinet>();
        Iterator<ArcCabinet> it = list.iterator();
        while (it.hasNext()) {
            ArcCabinet n = (ArcCabinet) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getCabinetId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ArcCabinet> list, ArcCabinet t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 查询智能柜一级
     *
     * @return 智能柜列表
     */
    @Override
    public List<ArcCabinet> selectArcCabinetAll() {
        return arcCabinetMapper.selectArcCabinetAll();
    }
}
